/*
 *   Copyright 2008 Francois Fernandes
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.googlecode.opendoclibrary.connector.internal;

import com.googlecode.opendoclibrary.AuthenticationFailedException;
import com.googlecode.opendoclibrary.connector.spi.IConnection;
import com.googlecode.opendoclibrary.connector.spi.IConnector;
import com.googlecode.opendoclibrary.connector.spi.IConnectorContext;

public class VMConnector implements IConnector
{
    private static class RegistrationSupport
    {
        private boolean connected;

        private final VMConnector connector;

        private final String name;

        public RegistrationSupport( String name, VMConnector connector )
        {
            if ( name == null )
            {
                throw new IllegalArgumentException( "name may not be null" );
            }
            if ( connector == null )
            {
                throw new IllegalArgumentException( "connector may not be null" );
            }
            this.name = name;
            this.connector = connector;
        }

        public synchronized void connect()
        {
            if ( !connected )
            {
                VMConnectorManager.getInstance().addConnector( name, connector );
                connected = true;
            }
        }

        public synchronized void disconnect()
        {
            if ( connected )
            {
                VMConnectorManager.getInstance().removeConnector( name, connector );
                connected = false;
            }
        }
    }

    private IConnectorContext ctx;

    private RegistrationSupport reg;

    public VMConnector()
    {
    }

    public IConnection newConnection( String username, String password ) throws AuthenticationFailedException
    {
        return ctx.newConnection( username, password );
    }

    @Override
    public void prepareShutdown()
    {
        reg.disconnect();
    }

    @Override
    public void shutdown()
    {
    }

    @Override
    public void startListening()
    {
        reg.connect();
    }

    @Override
    public void startup( IConnectorContext ctx )
    {
        this.ctx = ctx;
        reg = new RegistrationSupport( ctx.getName(), this );
    }

    @Override
    public void stopListening()
    {
        reg.disconnect();
    }
}
